import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Table, Divider, Modal, message } from 'antd';
import Form from './components/SearchForm';
import { templateStartOrEnd } from './service';
import { checkInit } from '@/utils/util';

export interface Props {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  buttons?: Array<any>,
  dict?: object
}

const confirm = Modal.confirm;
const ONE_PAGE_SIZE = 10;

@connect(({ report_template, loading, menu }) => ({
  list: report_template.list || {},
  dict: report_template.dict,
  buttons: menu.buttons,
  loading: loading.effects['report_template/queryPage']
}))
class Position extends Component<Props, any> {
  constructor(props) {
    super(props);
    this.initCurrent = this.initCurrent.bind(this);
  }
  state = {
    current: 1,
    selectedRowKeys: [],
    userIdList: []
  };

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;
    dispatch({
      type: 'report_template/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
        type: '2'
      },
    });
  }

  initCurrent() {
    this.setState({
      current: 1
    })
  }

  removeOption = (results) => {
    if(results) {
      this.setState({
        selectedRowKeys: []
      });
    }
  };

  onSelectChange = (selectedRowKeys, rowData) => {
    this.state.userIdList = [];
    this.setState({
      selectedRowKeys
    });
    rowData.forEach(item => {
      this.state.userIdList.push(item.id);
    });
  };

  startOrEnd(record) {
    let that = this;
    let tit = '模板启用';
    let txt = '确定启用该报表模板？';
    confirm({
      title: tit,
      content: txt,
      onOk() {
        let hasMsg = message.loading('');
        templateStartOrEnd(record.id).then(() => {
          hasMsg();
          message.success('操作成功', 1);
          that.queryData();
        });
      },
      onCancel() {},
      okText: "确认",
      cancelText: "取消"
    });
  }

  componentDidMount() {
    const { dispatch } = this.props;
    checkInit() ? dispatch({ type: `report_template/initCond` }) : this.queryData();
  }

  render() {
    const { buttons } = this.props;
    const btnList = {};
    if(Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys ,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: record.createType === '2'
      })
    };
    const { data = [], dataCnt } = this.props.list;
    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      id: item.id,
      name: item.name,
      status: item.status,
      statusName: item.statusName,
      createTime: item.createTime,
      childTypeName: item.childTypeName,
      creatorName: item.creatorName,
      createType: item.createType
      })
    ) : [];
    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: ONE_PAGE_SIZE,
      onChange: (current) => {
        this.setState({ current });
        this.queryData(current)
      },
    };
    const columns = [{
        title: '名称',
        dataIndex: 'name',
      }, {
        title: '状态',
        dataIndex: 'statusName',
      }, {
        title: '报表类型',
        dataIndex: 'childTypeName',
      }, {
        title: '系统默认模板',
        dataIndex: 'createType',
        render(v) {
          return v === '2' ? '是' : '否'
        }
      }, {
        title: '创建者',
        dataIndex: 'creatorName',
      }, {
        title: '创建日期',
        dataIndex: 'createTime',
      }, {
        title: '操作', key: 'x', render: (record) => {
        return (
          <div style={{display: 'flex'}}>
            {
              btnList['启用'] && record.status === '2' ? <>
                <span
                  style={{'color': '#0880DF', 'cursor': 'pointer'}}
                  onClick={this.startOrEnd.bind(this, record)}
                >启用</span>
                <Divider type="vertical" />
              </> : null
            }
            {
              btnList['编辑'] ? <>
                <Link to={`/data/report_template/${record.id}/update`}>编辑</Link>
                <Divider type="vertical" />
              </> : null
            }
            {
              btnList['查看'] ? <>
                <Link to={`/data/report_template/${record.id}/details`}>查看</Link>
              </> : null
            }
          </div>
        )}
      }];
    return (
      <div>
        <Form
          current={ this.state.current }
          initCurrent={this.initCurrent}
          removeOption={this.removeOption}
          userIdList={this.state.userIdList}
          new={!!btnList['新增']}/>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
          rowSelection={ rowSelection }
        />
      </div>
    );
  }
}

export default Position;
